package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.constant.FilePathContant;
import cn.net.shuxing.yifu.common.service.impl.OssCommonServiceImpl;
import cn.net.shuxing.yifu.common.util.FileUtil;
import cn.net.shuxing.yifu.common.util.JedisUtil;
import cn.net.shuxing.yifu.common.util.OssUtil;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import java.io.*;
import java.net.URL;
import java.util.Date;

@Service
public class OssCommonService implements OssCommonServiceImpl {

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private JedisUtil jedisUtil;

    public boolean uploadFile(String bucketName, String objectName, File file) {
        return OssUtil.uploadFile(bucketName, objectName, file);
    }

    public boolean uploadFile(String bucketName, String objectName, byte[] content, String suffix) {
        /** 构造本地临时文件 **/
        String realPath = new File("").getAbsolutePath();
        realPath += File.separator + suffix;
        File tempUploadFile = new File(realPath);
        if (tempUploadFile.exists())
            tempUploadFile.delete();
        try {
            tempUploadFile.createNewFile();
            FileOutputStream outputStream = new FileOutputStream(tempUploadFile);
            outputStream.write(content);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        if (!(tempUploadFile.exists() && tempUploadFile.length() > 0)) {
            return false;
        }

        /** 上传文件 **/
        OssUtil.uploadFile(bucketName, objectName, tempUploadFile);
        /** 删除临时文件 **/
        if (tempUploadFile.exists())
            tempUploadFile.delete();
        return true;
    }

    public String uploadLocalFile(String objectName, byte[] content, String suffix) {
        /** 构造本地临时文件 **/
        String realPath = new File(FilePathContant.localPath).getAbsolutePath();
        System.out.println("文件路径是：" + realPath);
        realPath += File.separator + objectName + suffix;
        File tempUploadFile = new File(realPath);
        if (tempUploadFile.exists())
            tempUploadFile.delete();
        try {
            tempUploadFile.createNewFile();
            FileOutputStream outputStream = new FileOutputStream(tempUploadFile);
            outputStream.write(content);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!(tempUploadFile.exists() && tempUploadFile.length() > 0)) {
            return null;
        }
        return tempUploadFile.getName();
    }

    public String getUrl(String bucketName, String objectName) {
        return getUrlObj(bucketName, objectName).toString();
    }

    public URL getUrlObj(String bucketName, String objectName) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAIQb8xLiRdju3q";
        String accessKeySecret = "1G6AFqff9UyONRy8zroKpu8UZjfnZj";

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 设置URL过期时间为1小时。
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);

        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }

    public byte[] getFileContent(String bucketName, String objectName) {
        String realPath = servletContext.getRealPath("");

        String suffix = FileUtil.getFileExtName(objectName);
        String filePath = realPath + File.separator + "tmpDownload" + suffix;
        File file = new File(filePath);
        if (file.exists())
            file.delete();
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        OssUtil.downloadFile(bucketName, objectName, file);
        byte[] content = new byte[(int) file.length()];
        try {
            FileInputStream inputStream = new FileInputStream(file);
            inputStream.read(content);
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    public boolean deleteFile(String bucketName, String objectName) {
        return OssUtil.deleteFile(bucketName, objectName);
    }

    public boolean exist(String bucketName, String objectName) {
        return OssUtil.exist(bucketName, objectName);
    }

}
